﻿using System;
using System.Collections;
using System.IO.Ports;
using System.Text;
using Model;

namespace TaxiDispatchClient.Service
{
    public class PhoneModemCom
    {
        public static readonly SerialPort serialPort = new SerialPort();
        readonly Queue snedDataQueue = new Queue();

        public PhoneModemCom()
        {
           
            try
            {
                string[] PortNames = SerialPort.GetPortNames();
                if (PortNames.Length > 0)
                {
                    if (serialPort.IsOpen)
                    {
                        serialPort.Close();
                    }
                    int minPort = int.MaxValue;
                    foreach (var portName in PortNames)
                    {
                        int temp = int.Parse(portName.Replace("COM", ""));
                        if(temp<minPort)
                        {
                            minPort = temp;
                        }
                    }
                    serialPort.PortName = "COM" + minPort;
                    serialPort.Open();
                    serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
                    ShowCallIdentification();
                }
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
            }

        }

        private Model.CallRecordsInfo _callRecords = new CallRecordsInfo();
        private string receString = string.Empty;

        private void serialPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {

                byte[] readBuffer = new byte[serialPort.BytesToRead];
                serialPort.Read(readBuffer, 0, readBuffer.Length);
                string tmpstr = Encoding.Default.GetString(readBuffer).ToUpper();
                Console.Write(tmpstr);
                if (tmpstr.Contains("R") && !tmpstr.Contains("RR"))
                {
                    if (MainForm.MainForm1 != null)
                    {
                        MainForm.MainForm1.InComingTelegram();
                    }

                }
                receString += tmpstr.Replace(" ", "");

                //\r\nRING\r\n\r\nNMBR = 15697923485\r\n\r\nRING\r\n\r\nRING
                if (receString.Contains("R") && !receString.Contains("RR"))
                {
                    //receString = receString.Replace("RING", "").Replace(" ", "");
                    string stratStr = "NMBR=";
                    if (receString.Contains(stratStr))
                    {
                        receString = receString.Replace("RING", "");
                        int stratindex = receString.IndexOf(stratStr, System.StringComparison.Ordinal);
                        receString = receString.Remove(0, stratindex);

                        int endindex = receString.IndexOf("\r\n", System.StringComparison.Ordinal);

                        if (endindex > 0)
                        {
                            int length = endindex - stratStr.Length;
                            string phonNubem = receString.Substring(stratStr.Length, length);

                            if (MainForm.MainForm1 != null)
                            {
                                MainForm.MainForm1.InComingTelegram(phonNubem);
                            }
                            //将记录插入到数据库
                            _callRecords.PhoneNumber = phonNubem;
                            _callRecords.CallTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                            MainForm.PositionService.CallRecordsAdd(_callRecords);
                            receString = string.Empty;
                        }
                    }
                }
                if (tmpstr.Contains("OK"))
                {
                    if (snedDataQueue.Count > 0)
                    {
                        string dsd = snedDataQueue.Dequeue().ToString();
                        serialPort.WriteLine(dsd);
                    }
                }

                //Console.WriteLine(receString);
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
            }
        }

        public bool CallPhoneNumber(string phoneNumber)
        {
            try
            {
                snedDataQueue.Clear();
                snedDataQueue.Enqueue("AT+FCLASS=8\r\n");
                snedDataQueue.Enqueue("ATDT" + phoneNumber + "\r\n");
                snedDataQueue.Enqueue("AT+VSP=1\r\n");
                snedDataQueue.Enqueue("AAT+VGM=255\r\n");
                snedDataQueue.Enqueue("AT+VLS=31\r\n");
                string temp = snedDataQueue.Dequeue().ToString();
                serialPort.WriteLine(temp);
                return true;
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
                return false;
            }
        }

        public bool Monitor(string phoneNumber)
        {
            try
            {
                snedDataQueue.Clear();
                snedDataQueue.Enqueue("AT+FCLASS=8\r\n");
                snedDataQueue.Enqueue("ATDT" + phoneNumber + "\r\n");
                snedDataQueue.Enqueue("AT+VSP=1\r\n");
                snedDataQueue.Enqueue("AAT+VGM=0\r\n");
                snedDataQueue.Enqueue("AT+VLS=31\r\n");
                string temp = snedDataQueue.Dequeue().ToString();
                serialPort.WriteLine(temp);
                return true;
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
                return false;
            }
        }

        public bool HangUp()
        {
            try
            {
                snedDataQueue.Clear();
                snedDataQueue.Enqueue("ATH0\r\n");
                string temp = snedDataQueue.Dequeue().ToString();
                serialPort.WriteLine(temp);
                return true;
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
                return false;
            }
        }

        public void ShowCallIdentification()
        {
            try
            {
                snedDataQueue.Clear();
                // snedDataQueue.Enqueue("AT+VSP=1\r\n");
                //  snedDataQueue.Enqueue("AAT+VGM=255\r\n");
                //  snedDataQueue.Enqueue("AT+VLS=31\r\n");
                snedDataQueue.Enqueue("AT+GCI=26\r\n");
                snedDataQueue.Enqueue("AT+VCID=1\r\n");
                string temp = snedDataQueue.Dequeue().ToString();
                serialPort.WriteLine(temp);
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
            }

        }

        public bool ChangeCom(string comName)
        {
            try
            {
                if (serialPort.IsOpen)
                {
                    serialPort.Close();
                }
                serialPort.PortName = comName;
                serialPort.Open();
                serialPort.DataReceived += new SerialDataReceivedEventHandler(serialPort_DataReceived);
                ShowCallIdentification();
                return true;
            }
            catch (Exception ex)
            {
                Common.CommonRoutine.HandlingExceptions(ex);
                return false;
            }
        }

        public void AnswerThePhone()
        {
            snedDataQueue.Clear();
            snedDataQueue.Enqueue("AT+FCLASS=8;+vls=1\r\n");
            snedDataQueue.Enqueue("AT+VSP=1\r\n");
            snedDataQueue.Enqueue("AAT+VGM=255\r\n");
            snedDataQueue.Enqueue("AT+VLS=31\r\n");
            string temp = snedDataQueue.Dequeue().ToString();
            serialPort.WriteLine(temp);
            //自动接听
            //serialPort.Write("AT+FCLASS=8\r\n");
            //serialPort.Write("at&d0\r\n");
            //serialPort.Write("ats0=1\r\n");
        }

    }
}
